﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for ReservationManager
/// </summary>
public class ReservationManager
{
    private debioscoopEntities db;

    public ReservationManager(debioscoopEntities db)
	{
        this.db = db;
	}

    public void addReservation(bestelling reservation)
    {
        db.bestellings.Add(reservation);
        executeQuery();
    }

    public bestelling getReservationActive(int reservationID)
    {
        TimeSpan timeNow = DateTime.Now.TimeOfDay;
        return db.bestellings.FirstOrDefault(b => b.bestelling_id == reservationID && b.active == true && b.afgehaald == false && b.datum == DateTime.Today.Date && b.tijd > timeNow);
    }

    public bestelling getReservation(int reservationID)
    {
        return db.bestellings.FirstOrDefault(b => b.bestelling_id == reservationID);
    }

    public List<bestelling> getReservations()
    {
        return db.bestellings.ToList();
    }

    public void PickupReservation(int reservationID)
    {
        bestelling reservation = db.bestellings.FirstOrDefault(b => b.bestelling_id == reservationID);
        reservation.afgehaald = true;
        reservation.betaald = true;
        executeQuery();
    }

    public void cancelReservation(int reservationID)
    {
        bestelling reservation = db.bestellings.FirstOrDefault(b => b.bestelling_id == reservationID);
        reservation.active = false;
        reservation.kaartjes.Clear();
        executeQuery();
    }

    public void executeQuery()
    {
        try
        {
            db.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e.InnerException);
        }
    }
}